package com.example.controller;

import com.example.dao.ConsultCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.Consult;
import com.example.pojo.PageBean;
import com.example.pojo.User;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@RestController
@RequestMapping("/consult")
@Slf4j
public class ConsultController {
    @Autowired
    private ConsultCrudRepository consultCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;

    @PostMapping("/addConsult")
    public Result add(@RequestBody Consult consult, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        if (user.getRole().equals("超级管理员")) {
            consult.setAgencyId(0);
            consult.setStatus("已发布");
        } else if (user.getRole().equals("机构管理员")) {
            consult.setAgencyId(user.getAgencyId());
            consult.setStatus("已发布");
        } else if (user.getRole().equals("学员")) {
            consult.setAgencyId(user.getAgencyId());
            consult.setUserId(user.getId());
            consult.setStatus("未发布");
        }
        Consult save = consultCrudRepository.save(consult);
        return Result.success(save);
    }

    @DeleteMapping("/deleteConsult")
    public Result delete(@RequestBody List<Integer> ids) {

        for (Integer id : ids) {
            consultCrudRepository.deleteById(id);
        }
        return Result.success("删除成功");
    }

    @PostMapping("/updateConsult")
    public Result update(@RequestBody Consult consult) {
        if(consult.getStatus().equals("未回复")&&consult.getAnswer()!=null){
            consult.setStatus("未发布");
        }
        Consult save = consultCrudRepository.save(consult);
        return Result.success(save);
    }

    @PostMapping("/getAllConsult")
    public Result getAllConsult(@RequestBody Consult consult,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();

        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.Direction.ASC, "id");
        System.out.println(consult);
        Page<Consult> coursePage = consultCrudRepository.findAll(new Specification<Consult>() {
            @Override
            public Predicate toPredicate(Root<Consult> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (consult != null) {
                    // 根据属性添加查询条件
                    if (consult.getQuestion() != null) {
                        predicate.getExpressions().add(cb.or(cb.like(root.get("question"), "%" + consult.getQuestion() + "%"),
                                cb.like(root.get("answer"), "%" + consult.getQuestion() + "%")));
                    }
                    if (consult.getId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("id"), consult.getId()));
                    }
                    if (user.getAgencyId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("agencyId"), user.getAgencyId()));
                    }
                    if (consult.getStatus() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("status"), consult.getStatus()));
                    }

                }
                return predicate;
            }
        }, pageable);
        List<Consult> Consults = coursePage.getContent();
        System.out.println(Consults);
        long elements = coursePage.getTotalElements();
        return Result.success(new PageBean(elements, Consults));
    }

    @GetMapping("/getConsultList")
    public Result getConsultList() {
        Iterable<Consult> all = consultCrudRepository.findAll();
        List<Consult> consultList = new ArrayList<>();
        for (Consult consult : all) {
            consultList.add(consult);
        }
        return Result.success(consultList);
    }

    //配置列表
    @GetMapping("/getConsultListForAgency")
    public Result getConsultListForAgency(Integer agencyId, Integer choose) {
        List<Consult> consultList = new ArrayList<>();
        if (choose == 0) {
            consultList.addAll(consultCrudRepository.unselectedConsult(agencyId));
        } else {
            consultList.addAll(consultCrudRepository.selectedConsult(agencyId));
        }
        return Result.success(consultList);
    }


    @PostMapping("/chooseConsult")
    public Result chooseConsult(@RequestBody List<Integer> ids, Integer agencyId) {

        for (Integer id : ids) {
            Consult consult = consultCrudRepository.findById(id).get();
            Consult newConsult = new Consult();
            newConsult.setAgencyId(agencyId);
            newConsult.setStatus("已发布");
            newConsult.setAnswer(consult.getAnswer());
            newConsult.setQuestion(consult.getQuestion());
            consultCrudRepository.save(newConsult);
        }

        return Result.success();
    }

    @PostMapping("/unchooseConsult")
    public Result unchooseConsult(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            consultCrudRepository.deleteById(id);
        }
        return Result.success("删除成功");
    }

    @GetMapping("/getConsultForUser")
    public Result getConsultForUser(@RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        List<Consult> consultList = new ArrayList<>();
        //学员获得所属机构发布的咨询列表
        if (user.getRole().equals("学员")) {
            consultList.addAll(consultCrudRepository.getConsultOfPublish(user.getAgencyId()));
            //获取自己的咨询

            consultList.addAll(consultCrudRepository.getConsultOfMy(user.getId()));
        } else if (user.getRole().equals("机构管理员")) {
            //机构管理员获取超级管理员发布的咨询列表

        }
        List<Consult> res = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        for (int i=0;i<consultList.size();i++){
            if(!set.contains(consultList.get(i).getId())){
                set.add(consultList.get(i).getId());
                res.add(consultList.get(i));
            }
        }
        return Result.success(res);
    }

    @PostMapping("/sendMessage")
    public Result sendMessage(@RequestHeader("token") String token, @RequestParam String question) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        Consult consult = new Consult(null, question, null, user.getAgencyId(), user.getId(), "未回复");
        consultCrudRepository.save(consult);
        return Result.success();
    }


}
